package com.guimin.fuwu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guimin.common.util.exception.BaseException;
import com.guimin.common.vo.R;
import com.guimin.fuwu.entity.GuiminService;
import com.guimin.fuwu.service.impl.GuiminServiceServiceImpl;
import com.guimin.fuwu.vo.serveListVo;
import com.guimin.user.dto.LoginInfoDto;
import com.guimin.user.entity.UserInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (GuiminService)表控制层
 *
 * @author makejava
 * @since 2021-11-17 10:13:03
 */
@RestController
@RequestMapping("/guiminService")
public class GuiminServiceController {

    @Resource
    private GuiminServiceServiceImpl guiMinServiceImpl;

    /**redis*/
    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 添加分类
     * @param request
     * @param service
     * @return
     */
    @PostMapping("/add/type")
    public R<?> addServe(HttpServletRequest request ,@RequestBody GuiminService service){
        if(service == null){
            return R.fail("参数为空");
        }
        LoginInfoDto userInfo= (LoginInfoDto) redisTemplate.opsForValue().get("token"+request.getHeader("token"));
        System.out.println("前端参数：\n"+service);
        return guiMinServiceImpl.addServe(userInfo.getId(),service);
    }


    /**
     * 添加服务
     * @param request
     * @param service
     * @return
     */
    @PostMapping("/add")
    public R<?> addServeType(HttpServletRequest request ,@RequestBody GuiminService service){
        if(service == null){
            return R.fail("参数为空");
        }

        LoginInfoDto userInfo= (LoginInfoDto) redisTemplate.opsForValue().get("token"+request.getHeader("token"));
        System.out.println("前端参数：\n"+service);
        return guiMinServiceImpl.addServeType(userInfo.getId(),service);
    }

    /**
     * 获取服务列表
     * @param request
     * @return
     */
    @PostMapping("/list")
    public R<List<GuiminService>> getServeList(HttpServletRequest request){
        LoginInfoDto userInfo= (LoginInfoDto) redisTemplate.opsForValue().get("token"+request.getHeader("token"));
        List<GuiminService> serveList = guiMinServiceImpl.getServeList(userInfo.getId());
        if(serveList.size() != 0){
            return R.success("查询成功",serveList);
        }
        return R.fail("差无数据");
    }

    /**
     * 获取服务列表
     * @param request
     * @return
     */
    @PostMapping("/list/f")
    public R<ArrayList<serveListVo>> getServeListF(HttpServletRequest request){
        LoginInfoDto userInfo= (LoginInfoDto) redisTemplate.opsForValue().get("token"+request.getHeader("token"));
        ArrayList<serveListVo> serveList = guiMinServiceImpl.getServeListF(userInfo.getId());
        if(serveList.size() != 0){
            return R.success("查询成功",serveList);
        }
        return R.fail("差无数据");
    }


    /**
     * 编辑
     * @param request
     * @param service
     * @return
     */
    @PostMapping("/alter")
    public R<?> alterServe(HttpServletRequest request,@RequestBody GuiminService service){
        System.out.println("前端参数："+service);
        LoginInfoDto userInfo= (LoginInfoDto) redisTemplate.opsForValue().get("token"+request.getHeader("token"));
        return guiMinServiceImpl.alterServe(userInfo.getId(),service);
    }

    /**
     * 删除
     * @param request
     * @return
     */
    @GetMapping("/delete")
    public R<?> deleteServe(HttpServletRequest request,@RequestParam Long id){
        System.out.println("前端参数："+id);
        LoginInfoDto userInfo= (LoginInfoDto) redisTemplate.opsForValue().get("token"+request.getHeader("token"));
        return guiMinServiceImpl.deleteServe(userInfo.getId(),id);
    }

    //头像上传
    @ResponseBody
    @RequestMapping("upload/pic")
    public Map uploadPic(MultipartFile file,HttpServletRequest request, @RequestParam String name){
        String prefix="";
        String dateStr="";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            System.out.println(file);
            if(file!=null){
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                Date date = new Date();
                String uuid = UUID.randomUUID()+"";
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
                dateStr = simpleDateFormat.format(date);

                //File new_file = new File("D:\\mycode\\pic\\"+service.getName()+"\\"+dateStr);
                //File new_file = new File("/user/java/pic/"+service.getName()+"/"+dateStr);   // (linux图片上传路径)

                String filepath = "D:\\guiMinFuWu\\pic\\"+name+"\\"+ dateStr+"\\"+uuid+"." + prefix;//再添加
                //String filepath = "/user/java/pic/"+service.getName()+"/" + dateStr+"/"+uuid+"." + prefix;    // (linux图片上传路径)

                File files=new File(filepath);

                //打印查看上传路径
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
                Map<String,Object> map2=new HashMap<>();
                Map<String,Object> map=new HashMap<>();
                map.put("code",0);
                map.put("msg","");
                map.put("data",map2);
               // map2.put("src","/user/java/pic/"+service.getName()+"/"+ dateStr+"/"+uuid+"." + prefix);
                map2.put("src","D:/guiMinFuWu/pic/"+name+"/"+ dateStr+"/"+uuid+"." + prefix);
                return map;
            }

        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }

        Map<String,Object> map=new HashMap<>();
        map.put("code",1);
        map.put("msg","");

        return map;

    }

    //头像转换格式
    @ResponseBody
    @GetMapping("/get/BaseImg")
    public String getBaseImg(String imgPath){

        if (imgPath==null){
            throw new BaseException("数据不存在");
        }
        File file = new File(imgPath);
        if (!file.exists()){
            throw new BaseException("头像文件不存在");
        }else if (file.isDirectory()){
            throw new BaseException("头像文件不存在");
        }

        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream( imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (data==null){
            throw new BaseException("头像不存在");
        }
        return Base64.getEncoder().encodeToString(data);
    }


}

